<?php
/**
 * 门店商品控制器
 * Created by PhpStorm.
 * Author: 芸众商城 www.yunzshop.com
 * Date: 2024/1/1
 * Time: 上午10:00
 */

namespace App\Http\Controllers\Api\store;

use App\Common\Components\ApiController;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Api\BaseApiController;

class GoodsController extends BaseApiController
{
    protected $publicController = ['Goods'];
    protected $publicAction = ['index', 'detail', 'create', 'update', 'delete', 'batchUpdate', 'getCategories', 'createCategory', 'updateCategory', 'deleteCategory', 'getBrands'];
    protected $ignoreAction = ['index', 'detail', 'getCategories', 'getBrands'];

    /**
     * 商品列表接口
     */
    public function index(Request $request)
    {
        $param = $request->input('param', []);
        $organid = $request->input('organid');
        
        // 获取请求参数
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 10;
        $title = $param['title'] ?? ''; // 商品名称
        $categoryId = $param['categoryId'] ?? ''; // 分类ID
        $status = $param['status'] ?? ''; // 商品状态
        $hasOption = $param['hasOption'] ?? ''; // 是否有规格
        $brandId = $param['brandId'] ?? ''; // 品牌ID
        $isSoldOut = $param['isSoldOut'] ?? ''; // 是否售罄（库存为0）
        
        // 构建查询条件
        $query = DB::table('ims_hhm_goods as g')
            ->leftJoin('ims_hhm_category as c1', 'g.category_id_1', '=', 'c1.id')
            ->leftJoin('ims_hhm_category as c2', 'g.category_id_2', '=', 'c2.id')
            // ->leftJoin('ims_hhm_brand as b', 'g.brand_id', '=', 'b.id')
            ->select([
                'g.id',
                'g.title',
                'g.alias',
                'g.thumb',
                'g.price',
                'g.market_price',
                'g.cost_price',
                'g.stock',
                'g.status',
                'g.has_option',
                'g.option_count',
                'g.real_sales',
                'g.virtual_sales',
                'g.show_sales',
                'g.created_at',
                'g.updated_at',
                'c1.name as category_1_name',
                'c2.name as category_2_name',
                'g.display_order',
                // 'b.name as brand_name'
            ]);
        
        // 添加店家ID筛选条件
        if (!empty($organid)) {
            $query->where('g.store_id', $organid);
        }
        
        // 添加筛选条件
        if (!empty($title)) {
            $query->where('g.title', 'like', '%' . $title . '%');
        }
        
        if (!empty($categoryId)) {
            $query->where(function($q) use ($categoryId) {
                $q->where('g.category_id_1', $categoryId)
                  ->orWhere('g.category_id_2', $categoryId);
            });
        }
        
        if ($status !== '') {
            $query->where('g.status', $status);
        }
        
        if ($hasOption !== '') {
            $query->where('g.has_option', $hasOption);
        }
        
        if (!empty($brandId)) {
            $query->where('g.brand_id', $brandId);
        }
        
        // 售罄筛选（库存为0）
        if ($isSoldOut == 1) {
            $query->where('g.stock', 0);
        }
        
        // 获取总数
        $total = $query->count();
        
        // 获取上架中和下架中的数量统计
        $statusStatsQuery = DB::table('ims_hhm_goods')
            ->select([
                DB::raw('SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as online_count'),
                DB::raw('SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as offline_count')
            ]);
        
        // 统计查询也添加店家ID过滤
        if (!empty($organid)) {
            $statusStatsQuery->where('store_id', $organid);
        }
        
        $statusStats = $statusStatsQuery->first();
        
        // 分页查询
        $goods = $query->orderBy('g.created_at', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get();
        
        // 处理商品状态显示
        $statusMap = [
            0 => '下架',
            1 => '上架'
        ];
        
        // 处理数据
        foreach ($goods as $item) {
            $item->status_text = $statusMap[$item->status] ?? '未知状态';
            $item->created_at = date('Y-m-d H:i:s', $item->created_at);
            $item->updated_at = date('Y-m-d H:i:s', $item->updated_at);
            $item->total_sales = $item->real_sales + $item->virtual_sales;
        }
        
        $data = [
            'list' => $goods,
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'pages' => ceil($total / $limit),
            'stats' => [
                'online_count' => $statusStats->online_count ?? 0,
                'offline_count' => $statusStats->offline_count ?? 0
            ]
        ];
        
        return $this->successJson('获取商品列表成功', $data);
    }
    
    /**
     * 商品详情接口
     */
    public function detail(Request $request)
    {
        $goodsId = $request->input('param.goodsId');
        $organid = $request->input('organid');
        
        if (empty($goodsId)) {
            return $this->errorJson('商品ID不能为空');
        }
        
        if (empty($organid)) {
            return $this->errorJson('店铺ID不能为空');
        }
        
        // 查询商品基本信息，添加店铺ID权限检查
        $goods = DB::table('ims_hhm_goods as g')
            ->leftJoin('ims_hhm_category as c1', 'g.category_id_1', '=', 'c1.id')
            ->leftJoin('ims_hhm_category as c2', 'g.category_id_2', '=', 'c2.id')
            // ->leftJoin('ims_hhm_category as c3', 'g.category_id_3', '=', 'c3.id')
            // ->leftJoin('ims_hhm_brand as b', 'g.brand_id', '=', 'b.id')
            ->where('g.id', $goodsId)
            ->where('g.store_id', $organid)
            ->select([
                'g.*',
                'c1.name as category_1_name',
                'c2.name as category_2_name',
                // 'c3.name as category_3_name',
                // 'b.name as brand_name'
            ])
            ->first();
        
        if (!$goods) {
            return $this->errorJson('商品不存在');
        }
        
        // 查询商品规格信息
        $specs = [];
        $options = [];
        
        if ($goods->has_option) {
            // 查询规格
            $specs = DB::table('ims_hhm_goods_spec')
                ->where('goods_id', $goodsId)
                ->orderBy('display_order')
                ->get();
            
            // 查询规格项
            foreach ($specs as $spec) {
                $spec->items = DB::table('ims_hhm_goods_spec_item')
                    ->where('spec_id', $spec->id)
                    ->orderBy('display_order')
                    ->get();
            }
            
            // 查询SKU选项
            $options = DB::table('ims_hhm_goods_option')
                ->where('goods_id', $goodsId)
                ->orderBy('display_order')
                ->get();
        }
        
        // 处理商品数据
        $goods->created_at = date('Y-m-d H:i:s', $goods->created_at);
        $goods->updated_at = date('Y-m-d H:i:s', $goods->updated_at);
        $goods->total_sales = $goods->real_sales + $goods->virtual_sales;
        
        $data = [
            'goods' => $goods,
            'specs' => $specs,
            'options' => $options
        ];
        
        return $this->successJson('获取商品详情成功', $data);
    }
    
    /**
     * 创建商品接口
     */
    public function create(Request $request)
    {
        $param = $request->input('param', []);
        $organid = $request->input('organid');
        if(empty($organid)){
            return $this->errorJson('店铺ID不能为空');
        }
        // 验证必填字段
        $validator = Validator::make($param, [
            'title' => 'required|string|max:300',
            'category_id_1' => 'required|integer',
            'price' => 'required|numeric|min:0',
            'stock' => 'required|integer|min:0',
            'thumb' => 'required|string',
        ], [
            'title.required' => '商品全称不能为空',
            'category_id_1.required' => '一级分类不能为空',
            'price.required' => '商品价格不能为空',
            'stock.required' => '库存不能为空',
            'thumb.required' => '商品主图不能为空',
        ]);
        
        if ($validator->fails()) {
            return $this->errorJson($validator->errors()->first());
        }
        
        try {
            DB::beginTransaction();
            
            // 准备商品数据
            $goodsData = [
                'uniacid' => 1, // 默认公众号ID
                'brand_id' => $param['brand_id'] ?? 0,
                'type' => $param['type'] ?? 1,
                'status' => $param['status'] ?? 1,
                'display_order' => $param['display_order'] ?? 0,
                'title' => $param['title'],
                'alias' => $param['alias'] ?? '',
                'sku' => $param['sku'] ?? '',
                'thumb' => $param['thumb'],
                'thumb_url' => isset($param['thumb_url']) ? json_encode($param['thumb_url']) : null,
                'detail_url' => isset($param['detail_url']) ? json_encode($param['detail_url']) : null,
                'video_url' => $param['video_url'] ?? null,
                'category_id_1' => $param['category_id_1'],
                'category_id_2' => $param['category_id_2'] ?? null,
                // 'category_id_3' => $param['category_id_3'] ?? null,
                'market_price' => $param['market_price'] ?? 0,
                'price' => $param['price'],
                'cost_price' => $param['cost_price'] ?? 0,
                'stock' => $param['stock'],
                'reduce_stock_method' => $param['reduce_stock_method'] ?? 0,
                'has_option' => $param['has_option'] ?? 0,
                'weight' => $param['weight'] ?? 0,
                'volume' => $param['volume'] ?? null,
                'goods_sn' => $param['goods_sn'] ?? '',
                'product_sn' => $param['product_sn'] ?? '',
                'description' => $param['description'] ?? '',
                'content' => $param['content'] ?? '',
                'min_buy' => $param['min_buy'] ?? 1,
                'max_buy' => $param['max_buy'] ?? 0,
                'is_limit' => $param['is_limit'] ?? 0,
                'need_address' => $param['need_address'] ?? 0,
                'no_refund' => $param['no_refund'] ?? 0,
                'created_at' => time(),
                'updated_at' => time(),
                'store_id' => $organid,
            ];
            
            // 插入商品
            $goodsId = DB::table('ims_hhm_goods')->insertGetId($goodsData);
            
            // 处理规格属性
            if (isset($param['has_option']) && $param['has_option'] == 1 && isset($param['specs'])) {
                $specMappings = $this->saveGoodsSpecs($goodsId, $param['specs']);
                
                // 保存规格明细（SKU）
                if (isset($param['options']) && is_array($param['options'])) {
                    $this->saveGoodsOptions($goodsId, $param['options'], $specMappings);
                }
            }
            
            // 处理商品分类关联
            $categoryIds = [];
            if (isset($param['category_ids']) && is_array($param['category_ids'])) {
                // 如果传了category_ids数组，使用它
                $categoryIds = $param['category_ids'];
            } else {
                // 否则根据category_id_1和category_id_2构建数组
                if (!empty($param['category_id_1'])) {
                    $categoryIds[] = $param['category_id_1'];
                }
                if (!empty($param['category_id_2'])) {
                    $categoryIds[] = $param['category_id_2'];
                }
            }
            
            if (!empty($categoryIds)) {
                $this->saveGoodsCategories($goodsId, $categoryIds);
            }
            
            DB::commit();
            
            return $this->successJson('商品创建成功', ['goods_id' => $goodsId]);
            
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorJson('商品创建失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 更新商品接口
     */
    public function update(Request $request)
    {
        $param = $request->input('param', []);
        $goodsId = $param['goods_id'] ?? 0;
        $type = $param['type'] ?? 1;
        $organid = $request->input('organid');
        
        if (empty($goodsId)) {
            return $this->errorJson('商品ID不能为空');
        }
        
        if (empty($organid)) {
            return $this->errorJson('店铺ID不能为空');
        }
        
        // 检查商品是否存在且属于当前店铺
        $goods = DB::table('ims_hhm_goods')
            ->where('id', $goodsId)
            ->where('store_id', $organid)
            ->first();
        if (!$goods) {
            return $this->errorJson('商品不存在或无权限操作');
        }
        
        try {
            DB::beginTransaction();
            
            // 准备更新数据
            $updateData = [];
            $allowedFields = [
                'title', 'alias', 'sku', 'thumb', 'thumb_url', 'video_url',
                'category_id_1', 'category_id_2',
                'market_price', 'price', 'cost_price', 'stock',
                'reduce_stock_method', 'has_option', 'weight', 'volume',
                'goods_sn', 'product_sn', 'description', 'content',
                'min_buy', 'max_buy', 'is_limit', 'need_address', 'no_refund',
                'status', 'display_order', 'detail_url'
            ];
            
            foreach ($allowedFields as $field) {
                if (isset($param[$field])) {
                    if (($field === 'thumb_url' || $field === 'detail_url') && is_array($param[$field])) {
                        $updateData[$field] = json_encode($param[$field]);
                    } else {
                        $updateData[$field] = $param[$field];
                    }
                }
            }
            
            $updateData['updated_at'] = time();
            
            // 更新商品
            DB::table('ims_hhm_goods')->where('id', $goodsId)->update($updateData);
            
            // 处理规格属性 - 只有明确传入specs参数时才处理规格更新
            if($type==2){
                if (isset($param['specs'])) {
                // 如果传入了specs参数，说明需要更新规格
                if (isset($param['has_option']) && $param['has_option'] == 1) {
                    // 删除原有规格
                    $specIds = DB::table('ims_hhm_goods_spec')->where('goods_id', $goodsId)->pluck('id');
                    if (!empty($specIds)) {
                        DB::table('ims_hhm_goods_spec_item')->whereIn('spec_id', $specIds)->delete();
                        DB::table('ims_hhm_goods_spec')->where('goods_id', $goodsId)->delete();
                    }
                    DB::table('ims_hhm_goods_option')->where('goods_id', $goodsId)->delete();
                    
                    // 保存新规格
                    $specMappings = $this->saveGoodsSpecs($goodsId, $param['specs']);
                    
                    // 保存规格明细（SKU）
                    if (isset($param['options']) && is_array($param['options'])) {
                        $this->saveGoodsOptions($goodsId, $param['options'], $specMappings);
                    }
                } else {
                    // has_option为0或未设置，删除所有规格
                    $specIds = DB::table('ims_hhm_goods_spec')->where('goods_id', $goodsId)->pluck('id');
                    if (!empty($specIds)) {
                        DB::table('ims_hhm_goods_spec_item')->whereIn('spec_id', $specIds)->delete();
                        DB::table('ims_hhm_goods_spec')->where('goods_id', $goodsId)->delete();
                    }
                    DB::table('ims_hhm_goods_option')->where('goods_id', $goodsId)->delete();
                }
            } elseif (isset($param['has_option']) && $param['has_option'] == 0) {
                // 如果明确设置has_option为0，但没有传入specs参数，也要删除规格
                $specIds = DB::table('ims_hhm_goods_spec')->where('goods_id', $goodsId)->pluck('id');
                if (!empty($specIds)) {
                    DB::table('ims_hhm_goods_spec_item')->whereIn('spec_id', $specIds)->delete();
                    DB::table('ims_hhm_goods_spec')->where('goods_id', $goodsId)->delete();
                }
                DB::table('ims_hhm_goods_option')->where('goods_id', $goodsId)->delete();
            }
            }
            // 如果既没有传入specs参数，has_option也不是0，则不处理规格（保持原有规格不变）
            
            // 处理商品分类关联 - 如果更新了分类信息
            if (isset($param['category_id_1']) || isset($param['category_id_2']) || (isset($param['category_ids']) && is_array($param['category_ids']))) {
                $categoryIds = [];
                if (isset($param['category_ids']) && is_array($param['category_ids'])) {
                    // 如果传了category_ids数组，使用它
                    $categoryIds = $param['category_ids'];
                } else {
                    // 否则根据category_id_1和category_id_2构建数组
                    if (isset($param['category_id_1']) && !empty($param['category_id_1'])) {
                        $categoryIds[] = $param['category_id_1'];
                    }
                    if (isset($param['category_id_2']) && !empty($param['category_id_2'])) {
                        $categoryIds[] = $param['category_id_2'];
                    }
                }
                
                if (!empty($categoryIds)) {
                    $this->saveGoodsCategories($goodsId, $categoryIds);
                }
            }
            
            DB::commit();
            
            return $this->successJson('商品更新成功');
            
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorJson('商品更新失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 删除商品接口
     */
    public function delete(Request $request)
    {
        $param = $request->input('param', []);
        $goodsId = $param['goods_id'] ?? 0;
        $organid = $request->input('organid');
        
        if (empty($goodsId)) {
            return $this->errorJson('商品ID不能为空');
        }
        
        if (empty($organid)) {
            return $this->errorJson('店铺ID不能为空');
        }
        
        // 检查商品是否存在且属于当前店铺
        $goods = DB::table('ims_hhm_goods')
            ->where('id', $goodsId)
            ->where('store_id', $organid)
            ->first();
        if (!$goods) {
            return $this->errorJson('商品不存在或无权限操作');
        }
        
        try {
            DB::beginTransaction();
            
            // 软删除商品
            DB::table('ims_hhm_goods')->where('id', $goodsId)->where('store_id', $organid)->update([
                'is_deleted' => 1,
                'deleted_at' => time(),
                'updated_at' => time()
            ]);
            
            DB::commit();
            
            return $this->successJson('商品删除成功');
            
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorJson('商品删除失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 批量更新商品接口
     */
    public function batchUpdate(Request $request)
    {
        $param = $request->input('param', []);
        $ids = $param['ids'] ?? [];
        $organid = $request->input('organid');
        
        if (empty($ids) || !is_array($ids)) {
            return $this->errorJson('请选择要更新的商品');
        }
        
        if (empty($organid)) {
            return $this->errorJson('店铺ID不能为空');
        }
        
        try {
            DB::beginTransaction();
            
            // 准备更新数据
            $updateData = [];
            $allowedFields = [
                'status',           // 上下架状态
                'category_id_1',    // 一级分类
                'category_id_2',    // 二级分类
                'display_order'     // 排序
            ];
            
            foreach ($allowedFields as $field) {
                if (isset($param[$field])) {
                    $updateData[$field] = $param[$field];
                }
            }
            
            if (empty($updateData)) {
                return $this->errorJson('没有要更新的数据');
            }
            
            $updateData['updated_at'] = time();
            
            // 批量更新商品（只更新属于当前店铺的商品）
            $affectedRows = DB::table('ims_hhm_goods')
                ->whereIn('id', $ids)
                ->where('store_id', $organid)
                ->update($updateData);
            
            // 如果更新了分类，同步更新 ims_hhm_goods_category 表
            if (isset($param['category_id_1']) || isset($param['category_id_2'])) {
                // 获取分类ID数组
                $categoryIds = [];
                if (isset($param['category_id_1']) && !empty($param['category_id_1'])) {
                    $categoryIds[] = $param['category_id_1'];
                }
                if (isset($param['category_id_2']) && !empty($param['category_id_2'])) {
                    $categoryIds[] = $param['category_id_2'];
                }
                
                // 为每个商品更新分类关联
                foreach ($ids as $goodsId) {
                    // 验证商品是否属于当前店铺
                    $goodsExists = DB::table('ims_hhm_goods')
                        ->where('id', $goodsId)
                        ->where('store_id', $organid)
                        ->exists();
                    
                    if ($goodsExists) {
                        $this->saveGoodsCategories($goodsId, $categoryIds);
                    }
                }
            }
            
            DB::commit();
            
            return $this->successJson('批量更新成功', ['affected_rows' => $affectedRows]);
            
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorJson('批量更新失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取分类列表
     */
    public function getCategories(Request $request)
    {
        $param = $request->input('param', []);
        $organid = $request->input('organid');
        
        // 构建查询
        $query = DB::table('ims_hhm_category')
            ->where('enabled', 1);
        
        // 添加店家ID筛选条件
        if (!empty($organid)) {
            $query->where('store_id', $organid);
        }
        
        // 根据层级过滤
        if (isset($param['level'])) {
            $query->where('level', $param['level']);
        }
        
        // 根据父级ID过滤
        if (isset($param['parent_id'])) {
            $query->where('parent_id', $param['parent_id']);
        }
        
        // 获取分类列表
        $categories = $query->orderBy('display_order')
            ->orderBy('id')
            ->get();
        
        // 转换时间戳为可读格式
        foreach ($categories as $category) {
            if ($category->created_at) {
                $category->created_at_text = date('Y-m-d H:i:s', $category->created_at);
            }
            if ($category->updated_at) {
                $category->updated_at_text = date('Y-m-d H:i:s', $category->updated_at);
            }
        }
        
        return $this->successJson('获取分类列表成功', [
            'list' => $categories,
            'total' => count($categories)
        ]);
    }
    
    /**
     * 创建分类
     */
    public function createCategory(Request $request)
    {
        $param = $request->input('param', []);
        $organid = $request->input('organid');
        
        if(empty($organid)){
            return $this->errorJson('店铺ID不能为空');
        }
        
        // 验证必填字段
        $validator = Validator::make($param, [
            'name' => 'required|string|max:100',
            'level' => 'required|integer|min:1|max:3',
        ], [
            'name.required' => '分类名称不能为空',
            'level.required' => '分类层级不能为空',
        ]);
        
        if ($validator->fails()) {
            return $this->errorJson($validator->errors()->first());
        }
        
        try {
            // 准备分类数据
            $categoryData = [
                'uniacid' => 1,
                'parent_id' => $param['parent_id'] ?? 0,
                'name' => $param['name'],
                'level' => $param['level'],
                'thumb' => $param['thumb'] ?? '',
                'description' => $param['description'] ?? '',
                'display_order' => $param['display_order'] ?? 0,
                'enabled' => $param['enabled'] ?? 1,
                'store_id' => $organid,
                'created_at' => time(),
                'updated_at' => time(),
            ];
            
            // 插入分类
            $categoryId = DB::table('ims_hhm_category')->insertGetId($categoryData);
            
            return $this->successJson('分类创建成功', ['category_id' => $categoryId]);
            
        } catch (\Exception $e) {
            return $this->errorJson('分类创建失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 更新分类
     */
    public function updateCategory(Request $request)
    {
        $param = $request->input('param', []);
        $organid = $request->input('organid');
        $categoryId = $param['id'] ?? 0;
        
        if (empty($categoryId)) {
            return $this->errorJson('分类ID不能为空');
        }
        
        if(empty($organid)){
            return $this->errorJson('店铺ID不能为空');
        }
        
        // 检查分类是否存在且属于当前店家
        $category = DB::table('ims_hhm_category')
            ->where('id', $categoryId)
            ->where('store_id', $organid)
            ->first();
        if (!$category) {
            return $this->errorJson('分类不存在或无权限操作');
        }
        
        try {
            // 准备更新数据
            $updateData = [];
            $allowedFields = ['parent_id', 'name', 'level', 'thumb', 'description', 'display_order', 'enabled'];
            
            foreach ($allowedFields as $field) {
                if (isset($param[$field])) {
                    $updateData[$field] = $param[$field];
                }
            }
            
            $updateData['updated_at'] = time();
            
            // 更新分类
            DB::table('ims_hhm_category')
                ->where('id', $categoryId)
                ->where('store_id', $organid)
                ->update($updateData);
            
            return $this->successJson('分类更新成功');
            
        } catch (\Exception $e) {
            return $this->errorJson('分类更新失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 删除分类
     */
    public function deleteCategory(Request $request)
    {
        $param = $request->input('param', []);
        $categoryId = $param['id'] ?? 0;
        
        if (empty($categoryId)) {
            return $this->errorJson('分类ID不能为空');
        }
        
        try {
            // 检查是否有子分类
            $hasChildren = DB::table('ims_hhm_category')
                ->where('parent_id', $categoryId)
                ->exists();
            
            if ($hasChildren) {
                return $this->errorJson('该分类下存在子分类，无法删除');
            }
            
            // 检查是否有商品使用该分类
            $hasGoods = DB::table('ims_hhm_goods')
                ->where(function($q) use ($categoryId) {
                    $q->where('category_id_1', $categoryId)
                      ->orWhere('category_id_2', $categoryId);
                    //   ->orWhere('category_id_3', $categoryId);
                })
                ->exists();
            
            if ($hasGoods) {
                return $this->errorJson('该分类下存在商品，无法删除');
            }
            
            // 删除分类
            DB::table('ims_hhm_category')->where('id', $categoryId)->delete();
            
            return $this->successJson('分类删除成功');
            
        } catch (\Exception $e) {
            return $this->errorJson('分类删除失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取品牌列表
     */
    public function getBrands()
    {
        $brands = DB::table('ims_hhm_brand')
            ->where('enabled', 1)
            ->orderBy('display_order')
            ->get();
        
        return $this->successJson('获取品牌列表成功', $brands);
    }
    
    /**
     * 保存商品规格
     */
    private function saveGoodsSpecs($goodsId, $specs)
    {
        $specIdMapping = []; // 用于存储规格标题到ID的映射
        $specItemIdMapping = []; // 用于存储规格项标题到ID的映射
        
        foreach ($specs as $specIndex => $spec) {
            $specId = DB::table('ims_hhm_goods_spec')->insertGetId([
                'uniacid' => 1,
                'goods_id' => $goodsId,
                'title' => $spec['title'],
                'description' => $spec['description'] ?? '',
                'display_type' => $spec['display_type'] ?? 0,
                'display_order' => $specIndex,
                'is_required' => $spec['is_required'] ?? 1,
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            
            // 记录规格标题到ID的映射
            $specIdMapping[$spec['title']] = $specId;
            
            // 保存规格项
            if (isset($spec['items']) && is_array($spec['items'])) {
                foreach ($spec['items'] as $itemIndex => $item) {
                    $specItemId = DB::table('ims_hhm_goods_spec_item')->insertGetId([
                        'uniacid' => 1,
                        'spec_id' => $specId,
                        'title' => $item['title'],
                        'thumb' => $item['thumb'] ?? '',
                        'color_value' => $item['color_value'] ?? '',
                        'display_order' => $itemIndex,
                        'show' => $item['show'] ?? 1,
                        'created_at' => time(),
                        'updated_at' => time(),
                    ]);
                    
                    // 记录规格项标题到ID的映射，使用复合键
                    $specItemIdMapping[$spec['title'] . '|' . $item['title']] = [
                        'spec_id' => $specId,
                        'spec_item_id' => $specItemId
                    ];
                }
            }
        }
        
        return [
            'spec_id_mapping' => $specIdMapping,
            'spec_item_id_mapping' => $specItemIdMapping
        ];
    }
    
    
    /**
     * 保存商品规格明细（SKU）
     */
    private function saveGoodsOptions($goodsId, $options, $specMappings = null)
    {
        foreach ($options as $index => $option) {
            // 构建规格组合标题
            $specTitles = [];
            $specsJson = [];
            
            if (isset($option['specs']) && is_array($option['specs'])) {
                foreach ($option['specs'] as $spec) {
                    if (isset($spec['title'])) {
                        $specTitles[] = $spec['title'];
                        
                        // 如果有映射关系，更新spec中的ID
                        $updatedSpec = $spec;
                        if ($specMappings && isset($specMappings['spec_id_mapping']) && isset($specMappings['spec_item_id_mapping'])) {
                            // 更新spec_id
                            if (isset($spec['spec_title']) && isset($specMappings['spec_id_mapping'][$spec['spec_title']])) {
                                $updatedSpec['spec_id'] = $specMappings['spec_id_mapping'][$spec['spec_title']];
                            }
                            
                            // 更新spec_item_id
                            if (isset($spec['spec_title']) && isset($spec['title'])) {
                                $mappingKey = $spec['spec_title'] . '|' . $spec['title'];
                                if (isset($specMappings['spec_item_id_mapping'][$mappingKey])) {
                                    $updatedSpec['spec_id'] = $specMappings['spec_item_id_mapping'][$mappingKey]['spec_id'];
                                    $updatedSpec['spec_item_id'] = $specMappings['spec_item_id_mapping'][$mappingKey]['spec_item_id'];
                                }
                            }
                        }
                        
                        $specsJson[] = $updatedSpec;
                    }
                }
            }
            
            DB::table('ims_hhm_goods_option')->insert([
                'uniacid' => 1,
                'goods_id' => $goodsId,
                'title' => $option['title'] ?? implode(',', $specTitles),
                'thumb' => $option['thumb'] ?? '',
                'product_price' => $option['product_price'] ?? 0,
                'market_price' => $option['market_price'] ?? 0,
                'cost_price' => $option['cost_price'] ?? 0,
                'stock' => $option['stock'] ?? 0,
                'withhold_stock' => $option['withhold_stock'] ?? 0,
                'weight' => $option['weight'] ?? 0,
                'volume' => $option['volume'] ?? 0,
                'goods_sn' => $option['goods_sn'] ?? '',
                'product_sn' => $option['product_sn'] ?? '',
                'sku_id' => $option['sku_id'] ?? '',
                'specs' => json_encode($specsJson),
                'spec_titles' => implode(',', $specTitles),
                'virtual' => $option['virtual'] ?? 0,
                'red_price' => $option['red_price'] ?? '',
                'display_order' => $index,
                'is_enabled' => $option['is_enabled'] ?? 1,
                'created_at' => time(),
                'updated_at' => time(),
            ]);
        }
    }
    
    /**
     * 保存商品分类关联
     * @param int $goodsId 商品ID
     * @param array $categoryIds 分类ID数组
     */
    private function saveGoodsCategories($goodsId, $categoryIds)
    {
        // 删除原有关联
        DB::table('ims_hhm_goods_category')->where('goods_id', $goodsId)->delete();
        
        if (empty($categoryIds) || !is_array($categoryIds)) {
            return;
        }
        
        // 过滤空值
        $categoryIds = array_filter($categoryIds);
        
        if (empty($categoryIds)) {
            return;
        }
        
        // 将分类ID数组转换为逗号分隔的字符串
        $categoryIdsStr = implode(',', $categoryIds);
        
        // 取最后一个分类ID作为子分类（更深层级的分类）
        $childCategoryId = end($categoryIds);
        
        // 插入一条记录，包含所有分类ID
        DB::table('ims_hhm_goods_category')->insert([
            'goods_id' => $goodsId,
            'category_id' => $childCategoryId,
            'category_ids' => $categoryIdsStr,
            'created_at' => time(),
            'updated_at' => time(),
        ]);
    }
    
    /**
     * 构建分类树
     */
    private function buildCategoryTree($categories)
    {
        $tree = [];
        $map = [];
        
        // 创建映射
        foreach ($categories as $category) {
            $map[$category->id] = $category;
            $map[$category->id]->children = [];
        }
        
        // 构建树结构
        foreach ($categories as $category) {
            if ($category->parent_id == 0) {
                $tree[] = $map[$category->id];
            } else {
                if (isset($map[$category->parent_id])) {
                    $map[$category->parent_id]->children[] = $map[$category->id];
                }
            }
        }
        
        return $tree;
    }
}
